package com.woniuxy.vuecli.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.vuecli.entity.ResponseResult;
import com.woniuxy.vuecli.service.PermissionService;
import com.woniuxy.vuecli.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author author
 * @Create 2024-01-19 14:45
 */
@Slf4j
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    PermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入AuthorizationInterceptor：");
        if (request.getMethod().equals("OPTIONS")) {
            log.info("OPTIONS预检请求，直接放行");
            return true;
        }
        String token = request.getHeader("token");
        //根据token查询当前用户对于的角色的权限permission
        List<String> permissions = permissionService.getByEid(Integer.parseInt(JwtUtil.getEid(token)));
        String url = request.getRequestURL().toString();
        boolean flag=false;
        for(String permission :permissions){
            if(url.contains(permission)){
                flag=true;
                break;
            }
        }

        if(flag){
            log.info("进入AuthorizationInterceptor：有操作权限，放行");
            return true;
        }else{
            log.info("进入AuthorizationInterceptor：没有操作权限，拦截");
                        ResponseResult<String> responseResult = new ResponseResult<>(403, "没有权限", null);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(responseResult));
            return false;
        }


//        if (!StringUtils.isEmpty(token) && JwtUtil.verify(token)) {
//            log.info("token有效，直接放行");
//            return true;
//        } else {
//            log.info("token无效，拦截");
//            ResponseResult<String> responseResult = new ResponseResult<>(401, "先登录", null);
//            response.setContentType("text/html;charset=utf-8");
//            response.getWriter().write(new ObjectMapper().writeValueAsString(responseResult));
//            return false;
//        }

    }
}
